<?php

namespace App\Controller;

use App\Exception\BusinessException;
use App\Service\WxUserLoginService;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;

class WxLoginController extends AbstractController
{
    #[Inject(WxUserLoginService::class)]
    protected WxUserLoginService $service;

    /**
     * 登录操作
     * @param $code
     * @return ResponseInterface
     * @throws GuzzleException
     */
    public function index($code): ResponseInterface
    {
        $from = $this->request->input('from');
        if (strlen($code) !== 32) {
            throw new BusinessException;
        }
        $user = $this->service->index($code, $from);
        return $this->response->json($user);
    }

    /**
     * 更新手机号，
     *
     */
    public function updatePhone(): ResponseInterface
    {
        $encryptedData = $this->request->input('encryptedData', '');
        $iv = $this->request->input('iv', '');
        if (!$encryptedData || !$iv) throw new BusinessException;
        $res = $this->service->updatePhoneByEncrypted($encryptedData, $iv, $this->user('id'));
        return $this->response->json($res);
    }
}